package net.huashitong.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

public class WordUtil {
    public static File createDoc(Map<?, ?> dataMap, String ftlName) {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(WordUtil.class, "/static/wordMould/");
        String name = ftlName;
        File f = new File(name);
        Template temp = null;
        Writer write = null;
        try {
            temp = configuration.getTemplate(ftlName, "UTF-8");
            write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
            temp.process(dataMap, write);
            write.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

    public static void exportWrodFile(HttpServletResponse response, Map map, String ftlName, String fiName) throws IOException {
        File file = null;
        InputStream fileInp = null;
        ServletOutputStream out = null;
        try {
            file = createDoc(map, ftlName);
            fileInp = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String fileName = fiName;
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int b = -1;
            while ((b = fileInp.read(buffer)) != -1) {
                out.write(buffer, 0, b);
            }
        } finally {
            if (fileInp != null) fileInp.close();
            if (out != null) out.close();
            if (file != null) file.delete(); // 删除临时文件
        }
    }
}
